import { createApp } from 'vue'
import App from './App.vue'
import router from './router/index'
import store from './store/index' //vuex
import pinia from './pinia/store.js' //pinia
import ElementPlus from 'element-plus'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
// import './assets/css/index.css'
import './style/rest.scss'
import './style/index.scss'
import 'element-plus/dist/index.css'
import 'virtual:svg-icons-register'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
createApp(App)
  .use(router)
  .use(ElementPlus, { locale: zhCn })
  .use(store)
  .use(pinia)
  .component('QuillEditor', QuillEditor)
  .mount('#app')
import { useStore } from './pinia/index'

let registerRouteFresh = true // 定义标识，记录路由是否添加
const pages = import.meta.glob('./views/**/index.vue')
const lauoytCom = import.meta.glob('./layout/index.vue')
const lauoyVla = lauoytCom['./layout/index.vue']
router.beforeEach(async (to, from, next) => {
  const pinias = useStore()
  let res = pinias.routeTree // 获取后台返回的路由树
  let arr = []
  res.forEach((value) => {
    let child = [] // 子路由数据格式处理
    if (value.children && value.children.length === 1) {
      value.children.filter((val) => {
        child.push({
          name: val.name,
          path: val.path,
          meta: { title: val.name },
          component: pages[val.component]
        })
      })
    }
    if (value.children && value.children.length > 1) {
      value.children.filter((val) => {
        child.push({
          name: val.name,
          path: val.path,
          meta: { title: val.name },
          component: pages[val.component]
        })
      })
    }
    arr.push({
      name: value.name,
      path: value.path,
      meta: { title: value.name },
      component: lauoyVla,
      children: child
    })
  })
  if (registerRouteFresh) {
    arr.forEach((val) => {
      router.addRoute(val)
      router.options.routes.push(val)
    })
    next({ ...to, replace: true })
    registerRouteFresh = false
  } else {
    next()
  }
})
